//
//  YDYTopicViewController.m
//  DYSisterAPP
//
//  Created by 杨德勇 on 16/8/4.
//  Copyright © 2016年 杨德勇. All rights reserved.
//

#import "YDYTopicViewController.h"

#import "YDYTopic.h"
#import <MJExtension.h>
#import <UIImageView+WebCache.h>
#import "YDYRefreshFooter.h"
#import "YDYRefreshHeader.h"
#import "YDYHTTPSessionManager.h"
#import "YDYTopicCell.h"
#import "YDYCommentViewController.h"
#import "YDYNewViewController.h"
@interface YDYTopicViewController ()
/** 数据源帖子 */
@property (nonatomic, strong) NSMutableArray<YDYTopic *> *topics;
/** 下拉刷新的label */
@property (nonatomic, weak) UILabel *label;
/** maxtime */
@property (nonatomic, copy) NSString *maxtime;
/** 网络请求（防止上拉和下拉冲突） */
@property (nonatomic, strong) YDYHTTPSessionManager *manager;
//声明这个方法只是为了能用点语法
-(NSString *)aParams;
@end

@implementation YDYTopicViewController
//identififer
static NSString * const YDYTopicCellId = @"topic";


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.tableView.backgroundColor = [UIColor lightGrayColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //注册cell
    UINib *nib= [UINib nibWithNibName:NSStringFromClass([YDYTopicCell class]) bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:YDYTopicCellId];
    
    //发送网络请求
    [self loadNewTopics];
    //设置下拉刷新
    [self setupRefresh];
    //监听通知
    [self setupNote];
    
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


#pragma mark -
#pragma mark -setup
-(void)setupNote{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tabbarBtnDidRepeatClick) name:YDYTabBarButtonDidRepeatClickNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(titleBtnDidRepeatClick) name:YDYTitleButtonDidRepeatClickNotification object:nil];
}
-(void)setupRefresh{
    //下拉刷新
    self.tableView.mj_header = [YDYRefreshHeader headerWithRefreshingTarget:self   refreshingAction:@selector(loadNewTopics)];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    //上拉刷新
    self.tableView.mj_footer = [YDYRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopics)];
    
}

#pragma mark -
#pragma mark -监听

-(void)titleBtnDidRepeatClick{
    [self tabbarBtnDidRepeatClick];
}
-(void)tabbarBtnDidRepeatClick{
    
    //判断控制器是否被创建，否则这个方法会被调用五次
    if (self.view.window == nil) return;
    //判断控制器是不是显示在用户面前
    if (![self.view ydy_intersectWithView:self.view.window])return;
    //下拉刷新
    [self.tableView.mj_header beginRefreshing];
    
}

#pragma mark -
#pragma mark -网络请求
-(void)loadNewTopics{

    //取消上次请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    //下面这个方法也可以停止，但是会把session关闭，在新的manager初始化之前都不能发请求了，最好不用
    //[self.manager invalidateSessionCancelingTasks:YES];
    
    //参数
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    params[@"a"] = self.aParams;
    params[@"c"] = @"data";
    params[@"type"] = @(self.type);
    
    //发送请求
    [self.manager GET:YDYcommentURL parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary*  _Nullable responseObject) {
        //        [responseObject writeToFile:@"/Users/Ydy/Desktop/未命名文件夹/b.plist" atomically:YES];
        
        //记录maxtime方便下一页加载
        self.maxtime = responseObject[@"info"][@"maxtime"];
        //字典转模型
        self.topics = [YDYTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        //重新加载数据
        [self.tableView reloadData];
        //关闭刷新视图
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        YDYLog(@"网络请求出错（加载数据）--%@",error);
        //关闭刷新视图
        [self.tableView.mj_header endRefreshing];
    }];
}
-(void)loadMoreTopics{

    //取消请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    //参数
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"data";
    params[@"type"] = @(self.type);
    params[@"maxtime"] = self.maxtime;
    //发送请求
    [self.manager GET:YDYcommentURL parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //字典转模型
        NSArray *moreTopics = [YDYTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [self.topics addObjectsFromArray:moreTopics];
        self.maxtime = responseObject[@"info"][@"maxtime"];
        //重新加载数据
        [self.tableView reloadData];
        //关闭刷新视图
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        YDYLog(@"网络请求出错（上啦刷新）--%@",error);
        //关闭刷新视图
        [self.tableView.mj_footer endRefreshing];
    }];
    
}
-(NSString *)aParams{
    //上一级控制器
    if (self.parentViewController.class == [YDYNewViewController class]) {
        return @"newlist";
    }
    
    return @"list";
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.topics.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YDYTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:YDYTopicCellId];
    cell.topic = self.topics[indexPath.row];
    return cell;
}



#pragma mark -
#pragma mark -delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  self.topics[indexPath.row].cellHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YDYCommentViewController *commentVC = [[YDYCommentViewController alloc]init];
    commentVC.topic = self.topics[indexPath.row];
    [self.navigationController pushViewController:commentVC animated:YES];
}

#pragma mark -
#pragma mark -懒加载
-(YDYHTTPSessionManager *)manager{
    if (_manager == nil) {
        return [YDYHTTPSessionManager manager];
    }
    return _manager;
}
#pragma mark -
#pragma mark -以下方法只是为了消除系统警告
-(YDYTopicType)type{
    return 0;
}

@end
